<?php
namespace app\wechat\controller;

use tp5_lib\wechat\utility\WechatOAuth;
use tp5_lib\wechat\model\WechatUserModel;
use tp5_lib\user\extension\OutsideController;
use tp5_lib\wechat\model\WechatUserTokenModel;

/**
 * 微信扫码登录
 * 适用于PC网站
 */
class IndexController extends OutsideController
{
    public function __get($name)
    {
        if($name === "outside"){
            if(empty($this->_outside)){
                $this->_outside=new WechatUserModel();
            }
            return $this->_outside;
        }
        return parent::__get($name);
    }
    private $appid="wx64c9c489b30b989d";
    private $appSecret="0795f080a7a8f7b1a45a46320ed38ed3";
    /**
     * 扫码登录页面
     */
    public function index()
    {
        session("wechat_login_redirect_url",input("redirect_url",""));
        $redirect_uri= "http://tp5.1620428040.xyz/wechat/index/receivecode";
        $url=WechatOAuth::alloc($this->appid,$this->appSecret)
            ->getScanLoginUrl($redirect_uri,"423423523");
        $this->redirect($url);
    }
    /**
     * 接收code页面
     * 为了防止微信重复发送code造成的bug，这里添加一次额外的跳转
     */
    public function receiveCode()
    {
        $this->redirect("updateInfo",input());
    }
    /**
     * 实际接收code的页面
     * 更新用户信息并判断是否绑定
     */
    public function updateInfo(){
        $code=input("code");
        $wechat=WechatOAuth::alloc($this->appid,$this->appSecret);

        $token_info=$wechat->getAccessToken($code);
        if(isset($token_info["errcode"])){
            $this->error("微信第三方登录失败");
        }
        $token=new WechatUserTokenModel();
        $token_info["time"]=time();
        $token_info["source"]="scan";
        $token->db()->insert($token_info);

        $user_info=$wechat->getUserInfo($token_info["openid"],$token_info["access_token"]);
        if(isset($user_info["errcode"])){
            $this->error("获取用户信息失败");
        }
        $user=new WechatUserModel();
        if(isset($user_info["unionid"])){
            $record=$user->db()->where(["unionid"=>$user_info["unionid"]])->order("id","desc")->find();
        }
        else{
            $record=$user->db()->where(["openid"=>$user_info["openid"]])->order("id","desc")->find();
        }
        $user_info["update_time"]=time();
        $user_info["privilege"]=json_encode($user_info["privilege"]);
        if($record){
            $user->db()->where(["id"=>$record["id"]])->update($user_info);
            if($record["user_id"]){
                $user=$this->logic->doLogin($record["user_id"]);
                $this->loginRedirect($user);
            }
            else{
                $this->redirect("bindAccount",["id"=>$record["id"]]);
            }   
        }
        else{
            $user_info["create_time"]=time();
            $id=$user->db()->insertGetId($user_info);
            $this->redirect("bindAccount",["id"=>$id]);
        }
    }
    protected function convertUserInfo($data)
    {
        $user=[
            "username"=>"wechat_".time(),
            "mobile"=>"",
            "email"=>"",
            "nickname"=>$data["nickname"],
            "avatar"=>$data["headimgurl"],
            "signature"=>"",
            "sex"=>$data["sex"],
            "birthday"=>"",
            "url"=>"",
        ];
        return $user;
    }
}
